<template>
  <div>
    <div class="article-meta">
      <nuxt-link :to="`/profile/${article.author.username}`">
        <user-image :src="article.author.image" />
      </nuxt-link>
      <div class="info">
        <nuxt-link :to="`/profile/${article.author.username}`" class="author">{{article.author.username}}</nuxt-link>
        <span class="date">{{article.createdAt | format('MMMM DD, YYYY')}}</span>
      </div>
      <button
        class="btn btn-outline-primary btn-sm pull-xs-right"
        :class="{
                active: article.favorited
              }"
        :style="{
            disabled: this.isFavoriting
        }"
        @click="tiggerFavorite(article)"
      >
        <i class="ion-heart"></i>
        {{article.favoritesCount}}
      </button>
    </div>
    <nuxt-link :to="`/article/${article.slug}`" class="preview-link">
      <h1>{{article.title}}</h1>
      <p>{{article.description}}</p>
      <span>Read more...</span>
    </nuxt-link>
  </div>
</template>

<script>
import { favoriteArticle, unfavoriteArticle } from '@/api/article.js'
import { mapState } from 'vuex'
import UserImage from './userImage.vue'
export default {
  name: 'ArticleItem',
  components: { UserImage },
  props: {
    article: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      isFavoriting: false,
    }
  },
  methods: {
    async tiggerFavorite(article) {
      if (!this.user) {
        this.$router.push({
          name: 'login',
        })
        return 
      }
      this.isFavoriting = true
      const { slug, favorited } = article
      const request = favorited ? unfavoriteArticle : favoriteArticle
      const { data } = await request(slug)
      if (data) {
        const { article: art } = data
        article.favorited = art.favorited
        article.favoritesCount = art.favoritesCount
      }

      this.isFavoriting = false
    },
  },
  computed: {
    ...mapState(['user']),
  },
}
</script>